package com.sky.aspect;

import com.fasterxml.jackson.databind.ser.Serializers;
import com.sky.annotation.AutoFill;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.val;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * 自动填充
 */
@Component
@Aspect
public class AutoFillAspect {

    /**
     * 定义切入点AutoFill注解
     */
    @Pointcut("@annotation(com.sky.annotation.AutoFill)")
    public void autoFillPointCut() {
    }

    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) {
        //获取参数
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            //实体类的参数才需要处理
            Class<?> cls = arg.getClass();
            String pkgName = cls.getPackageName();
            if ("com.sky.entity".equals(pkgName)) {
                System.out.println(cls);
                //获取
                MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
                //获取方法
                Method method = methodSignature.getMethod();
                AutoFill autoFill = method.getAnnotation(AutoFill.class);
                OperationType operationType = autoFill.value();
                System.out.println(operationType);
                try {
                    Method setCreateTime = cls.getDeclaredMethod("setCreateTime", LocalDateTime.class);
                    Method setUpdateTime = cls.getDeclaredMethod("setUpdateTime", LocalDateTime.class);
                    Method setCreateUser = cls.getDeclaredMethod("setCreateUser", Long.class);
                    Method setUpdateUser = cls.getDeclaredMethod("setUpdateUser", Long.class);
                    LocalDateTime now = LocalDateTime.now();
                    Long loginUserId = BaseContext.getCurrentId();
                    switch (operationType) {
                        case INSERT:
                            setCreateTime.invoke(arg, now);
                            setUpdateTime.invoke(arg, now);
                            setCreateUser.invoke(arg, loginUserId);
                            setUpdateUser.invoke(arg, loginUserId);
                            break;//4个set
                        case UPDATE:
                            setUpdateTime.invoke(arg, now);
                            setUpdateUser.invoke(arg, loginUserId);
                            break;//2个set
                    }

                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}